Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Ternary Operator

Ternary operator example

A ternary statement in Java is a compact way to express a conditional operation. It consists of three parts: the condition, the value to return if the condition is true, and the value to return if the condition is false. Here are some examples of ternary statements in Java:

Example 1. Assigning a Value Based on a Condition:

Category using ternary
public class Main{ public void example{ int age = 20; String message = (age >= 18) ? "You are an adult" : "You are a minor"; System.out.println(message); } }

Output

You are an adult
In this example, the value of message is assigned based on the condition age >= 18. If the condition is true, it assigns "You are an adult" to message, otherwise, it assigns "You are a minor."

Example 2. Returning a Value from a Method:

Approval status
public class Ternary{ public String getApprovalStatus(boolean isApproved) { return (isApproved) ? "Approved" : "Not Approved"; } }

Output

*considering isApproved as true
Approved
In this method, getApprovalStatus returns "Approved" if the isApproved parameter is true, and "Not Approved" if it's false.

Example 3. Calculating the Maximum of Two Numbers:

Maximun number using ternary
public class Main{ public void example{ int num1 = 25; int num2 = 30; int max = (num1 > num2) ? num1 : num2; System.out.println("The maximum number is: " + max); } }

Output

The maximum number is: 30
This code calculates and prints the maximum of num1 and num2 using a ternary statement.

Example 4. Converting a Numeric Grade to a Letter Grade:

Grading in java
public class Main{ public void example{ int numericGrade = 85; char letterGrade = (numericGrade >= 90) ? 'A' : (numericGrade >= 80) ? 'B' : 'C'; System.out.println("Your letter grade is: " + letterGrade); } }

Output

Your letter grade is: B
Here, a nested ternary statement is used to convert a numeric grade to a letter grade based on certain criteria.

Example 5. Checking for Null and Providing a Default Value:

message
public class Main{ public void example{ String name = null; String displayName = (name != null) ? name : "Guest"; System.out.println("Welcome, " + displayName); } }

Output

Welcome, Guest
In this example, it checks if the name variable is null and assigns "Guest" as the default value if it is. Ternary statements are concise and can be handy for simple conditional operations where you want to assign or return values based on a condition. However, they should be used judiciously to maintain code readability.

  📌TAGS

★ternary ★ternary statement ★ternary in java ★java ★ternary operator example ★ternary operator ★operator

Tutorials